package com.ddmh.gateway.config;

import com.alibaba.cloud.nacos.NacosConfigProperties;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Properties;

/**
 * 将configService交由spring管理
 * @author : jiagang
 * @date : Created in 2022/7/20 15:27
 */
@Configuration
public class GatewayConfigServiceConfig {
    /**
     * 常量
     */
    private static final String PROPERTIES_SERVER_ADDR = "serverAddr";
    private static final String PROPERTIES_NAMESPACE = "namespace";
    private static final String PROPERTIES_GROUP = "group";
    private static final String PROPERTIES_USERNAME = "username";
    private static final String PROPERTIES_PASSWORD = "password";

    @Autowired
    private GatewayRouteConfig configProperties;

    @Autowired
    private NacosConfigProperties nacosConfigProperties;

    @Bean
    public ConfigService configService() throws NacosException {
        Properties properties = new Properties();
        properties.setProperty(PROPERTIES_SERVER_ADDR, nacosConfigProperties.getServerAddr());
        properties.setProperty(PROPERTIES_NAMESPACE, configProperties.getNamespace());
        if (StringUtils.isNotBlank(configProperties.getGroup())) {
            properties.put(PROPERTIES_GROUP, configProperties.getGroup());
        }
        if (StringUtils.isNotBlank(configProperties.getUsername())) {
            properties.put(PROPERTIES_USERNAME, configProperties.getUsername());
        }
        if (StringUtils.isNotBlank(configProperties.getPassword())) {
            properties.put(PROPERTIES_PASSWORD, configProperties.getPassword());
        }
        return NacosFactory.createConfigService(properties);
    }
}
